package controllers

import (
	"encoding/json"
	"golanger.com/utils"
	"jk/jklog"
	"models"
	"net/http"
)

type PageDB struct {
	Application
}

func init() {
	App.RegisterController("db/", PageDB{})
}

var l = jklog.Lext("[work]", -1)

type dbs struct {
	item []dbitem
}
type dbitem struct {
	Name string
}

func (p *PageDB) Db(rw http.ResponseWriter, req *http.Request) {
	p.Document.Title = "db deal"
	jkdb := models.New(models.DBGLOBAL)
	if jkdb == nil {
		l.Errorln("jkdb is nil")
		return
	}
	s := jkdb.JKDBS()
	/* the html range must interface, so convert to interface */
	var dbs_i []dbitem
	for _, v := range s {
		i := dbitem{Name: v}
		dbs_i = append(dbs_i, i)
	}

	body := utils.M{}
	body["dbs"] = dbs_i
	p.Body = body
}

func (p *PageDB) GetCollections(rw http.ResponseWriter, req *http.Request) {
	var dbs_i []dbitem
	status := utils.M{
		"status": 0,
	}
	if req.Method == "GET" {
		if _, ok := p.GET["ajax"]; ok {
			dbname := p.GET["col"]

			jkdb := models.New(models.DBGLOBAL)
			if jkdb == nil {
				l.Errorln("jkdb is nil")
				status["status"] = -1
			} else {
				c := jkdb.JKCollections(dbname)
				for _, v := range c {
					i := dbitem{Name: v}
					dbs_i = append(dbs_i, i)
				}
			}
		}
	}
	var result []byte
	if status["status"] == 0 {
		result, _ = json.Marshal(dbs_i)
	} else {
		result, _ = json.Marshal(status)
	}
	rw.Write(result)
}
